let recorder;
let recordingData = [];
let recorderStream;
let startTime;

/**
 * 混合音频
 * */
function mixer(stream1, stream2) {
    const ctx = new AudioContext();
    const dest = ctx.createMediaStreamDestination();

    if (stream1.getAudioTracks().length > 0)
        ctx.createMediaStreamSource(stream1).connect(dest);

    if (stream2.getAudioTracks().length > 0)
        ctx.createMediaStreamSource(stream2).connect(dest);

    let tracks = dest.stream.getTracks();
    tracks = tracks.concat(stream1.getVideoTracks()).concat(stream2.getVideoTracks());

    return new MediaStream(tracks)

}

/**
 * 根据URL和时间戳中的Jitsi房间名称返回文件名
 *
 */
function getFilename() {
    const now = new Date();
    const timestamp = now.toISOString();
    const room = new RegExp(/(^.+)\s\|/).exec(document.title);
    if (room && room[1] !== "")
        return `${room[1]}_${timestamp}`;
    else
        return `recording_${timestamp}`;
}

/**
 * 检查浏览器支持的编码
 *
 */
export function checkCodecsSupported() {
   
    let options = {mimeType: 'video/webm;codecs=vp9,opus'};
    try{
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            console.log(`${options.mimeType} is not supported`);
            options = {mimeType: 'video/webm;codecs=vp8,opus'};
            if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                console.log(`${options.mimeType} is not supported`);
                options = {mimeType: 'video/webm'};
                if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                    console.log(`${options.mimeType} is not supported`);
                    options = {mimeType: ''};
                }
            }
        }
    } catch (e) {
        alert("请升级你的浏览器");
        return false;
    }
    return options;
}

/**
 * 开始录制
 * */

const [width, height, frameRate] = [1280, 720, 15];


export async function recordStart(){
    console.log("widthwidthwidthwidthwidthwidthwidthwidthwidthwidthwidth", width);

    const options = checkCodecsSupported();

        let gumStream, gdmStream;
        recordingData = [];

        try {
            gumStream = await navigator.mediaDevices.getUserMedia({
                video: false, audio: {
                    echoCancellation: {exact: true}
                }
            });
            gdmStream = await navigator.mediaDevices.getDisplayMedia({
                video: {
                    width,
                    height,
                    frameRate
                }, audio: {
                    echoCancellation: true
                }
            });

            recorderStream = gumStream ? mixer(gumStream, gdmStream) : gdmStream;

            recorder = new MediaRecorder(recorderStream, options);
            recorder.start(1000);
            startTime = Date.now();
    

        } catch (e) {
            console.log("capture failure", e);
            return
        }


    recorder.ondataavailable = e => {
        if (e.data && e.data.size > 0) {
            recordingData.push(e.data);


            let blob = new Blob([e.data], {type: 'video/webm'});
            let formData = new FormData();
            formData.append("video_file", blob);
            formData.append("requestId", "1234567");

            $.ajax({
                url: 'http://127.0.0.1:8080/video_api/oss/upload',
                dataType: 'json',
                type: 'POST',
                async: false,
                data: formData,
                processData: false, // 使数据不做处理
                contentType: false, // 不要设置Content-Type请求头
                success: function (data) {
                    console.log(data);
                    if (data.status == 'ok') {
                        alert('上传成功！');
                    }

                },
                log: function (response) {
                    console.log(response);
                }
            });

        }

    };

    recorder.onstop = () => {
        recorderStream.getTracks().forEach(track => track.stop());
        gumStream.getTracks().forEach(track => track.stop());
        gdmStream.getTracks().forEach(track => track.stop());

        var duration = Date.now() - startTime;
        var buggyBlob = new Blob(recordingData, { type: 'video/webm' });
        
        ysFixWebmDuration(buggyBlob, duration, function(fixedBlob) {
            playback.hidden = !playback.hidden;
            if (!isPlaying && !playback.hidden) {
                playback.src = window.URL.createObjectURL(fixedBlob);
                playback.play();
                play.innerText = "Hide";
            } else
                play.innerText = "Play";
        
        });
    };

    recorderStream.addEventListener('inactive', () => {
        console.log('Capture stream inactive');
        stopCapture();
    });


    console.log("started recording");
}


/**
 * 停止录制
 */

export function stopCapture() {
    console.log("Stopping recording");
    recorder.stop();
}

/**
 *
 *  播放录制
 */


let isPlaying = false;

function autoPlay() {
    playback.src = window.URL.createObjectURL(new Blob(recordingData, {type: 'video/webm'}));
    playback.play();
}
// const play = document.getElementById('recordPlay');
// play.addEventListener('click', () => {
//     playback.hidden = !playback.hidden;
//     if (!isPlaying && !playback.hidden) {
//         playback.src = window.URL.createObjectURL(new Blob(recordingData, {type: 'video/webm'}));
//         playback.play();
//         play.innerText = "Hide";
//     } else
//         play.innerText = "Play";

// });

// const playback = document.getElementById('recordPlayback');
// // 添加处理事件
// playback.addEventListener('play', () => {
//     isPlaying = true
// });
// playback.addEventListener('pause', () => {
//     isPlaying = false
// });
// playback.addEventListener('playing', () => {
//     isPlaying = true
// });
// playback.addEventListener('ended', () => {
//     isPlaying = false
// });

/**
 * 保存录制
 * */
// const save = document.getElementById('recordSave');
// save.addEventListener('click', () => {
//     const blob = new Blob(recordingData, {type: 'video/webm'});
//     const url = window.URL.createObjectURL(blob);
//     const a = document.createElement('a');
//     a.style.display = 'none';
//     a.href = url;
//     a.download = `${getFilename()}.webm`;
//     document.body.appendChild(a);
//     a.click();
//     setTimeout(() => {
//         document.body.removeChild(a);
//         window.URL.revokeObjectURL(url);
//         console.log(`${a.download} save option shown`);
//     }, 100);
// });
